package com.pajk.user.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Created by chenhaihua on 14-4-29.
 */
public class DateUtil {
    /** 年月日(无下划线) yyyyMMdd */
    public static final String DTYEAR  = "yyyy";

    /** 年月日(无下划线) yyyyMMdd */
    public static final String DTMONTH  = "yyyyMM";

    /** 年月日(无下划线) yyyyMMdd */
    public static final String DTSHORT  = "yyyyMMdd";

    /** 年月日时(无下划线) yyyyMMddHH */
    public static final String DTHOUR   = "yyyyMMddHH";

    /** 年月日时分(无下划线) yyyyMMddHHmm */
    public static final String DTMIDDLE = "yyyyMMddHHmm";

    /** 年月日时分秒(无下划线) yyyyMMddHHmmss */
    public static final String DTLONG   = "yyyyMMddHHmmss";

    public static String format(Date date, String format) {
        return new SimpleDateFormat(format, Locale.SIMPLIFIED_CHINESE).format(date);
    }

    public static Date stringToDate(String stringDate, String format) {
        if (stringDate == null) {
            return null;
        }
        try {
            return new SimpleDateFormat(format).parse(stringDate);
        } catch (ParseException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static Date getFirstDayOfWeek(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.setFirstDayOfWeek(Calendar.SUNDAY);
        cal.set(Calendar.DAY_OF_WEEK, 1);
        cal.setMinimalDaysInFirstWeek(1);
        return cal.getTime();
    }

    public static int getWeekOfYear(Date date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.setFirstDayOfWeek(Calendar.SUNDAY);
        cal.setMinimalDaysInFirstWeek(1);
        return cal.get(Calendar.WEEK_OF_YEAR);
    }
}
